package ntd.util.frame.task.handle.iot;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.task.Task;
import ntd.task.bo.TaskInfo;
import ntd.util.UtilThreadPool;
import com.modular.iot.bean.ThingsDeviceCmdDo;
import com.modular.iot.tool.ToolIotCmd;
import ntd.util.modular.data.util.handle.tool.Tool212;
import ntd.util.str.ToolCutMsg;

import java.util.List;
import java.util.Map;

public class TaskIotCmdExe implements Task {

    @Override
    public TaskInfo info() {
        return new TaskInfo("任务-IOT-指令执行器", "task-task-iot-cmd-exe", this);
    }

    @Override
    public void execute(Object o) {
        List<ThingsDeviceCmdDo> thingsDeviceCmdDos = ToolIotCmd.listCmd();
        Map<String, List<ThingsDeviceCmdDo>> thingsMap =
                CollStreamUtil.groupByKey(thingsDeviceCmdDos, ThingsDeviceCmdDo::getDeviceCode);

        // 区分不同设备采用不同线程，单次指令休眠 0.6s
        for (List<ThingsDeviceCmdDo> value : thingsMap.values()) {
            UtilThreadPool.run(() -> {
                for (ThingsDeviceCmdDo thingsDeviceCmdDo : value) {
                    ToolIotCmd.exeCmd(thingsDeviceCmdDo);
                    ThreadUtil.sleep(600);
                }
            });
        }
    }


    public static void main(String[] args) {
        String str = "##0082QN=20230207114652322;ST=32;CN=9802;PW=123456;MN=41010501G00001;Flag=5;CP=&&ExeRtn=0F&&3300\r\n" +
                "##0257ST=32;CN=2011;QN=20230302182453074;PW=123456;MN=41010501G00001;Flag=0;CP=&&DataTime=20230302182453;B01-Rtd=0.00,B01-Flag=N;BO2-Cou=_,BO2-Flag=N;011-Rtd=0.000000,011-Flag=N;101-Rtd=0.00";
        String str1 = "##0082QN=20230207114652322;ST=32;CN=9802;PW=123456;MN=41010501G00001;Flag=5;CP=&&ExeRtn=0F&&3300\r\n" +
                "\n";

        StaticLog.info(str);

        ToolCutMsg me = ToolCutMsg.me(Tool212.getCutMsg());

        List<String> strings = me.parseDeep(str);
        List<String> strings1 = me.parseDeep(str1);

        StaticLog.info(JSONUtil.toJsonStr(strings));
        StaticLog.info(JSONUtil.toJsonStr(strings1));

    }
}
